package com.lanou3g.ptp.teacher.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lanou.ptp.role_teacher.RoleTeacherService;
import com.lanou3g.ptp.base.service.BaseService;
import com.lanou3g.ptp.entity.*;
import com.lanou3g.ptp.organize.service.CollegeService;
import com.lanou3g.ptp.organize.service.SchoolService;
import com.lanou3g.ptp.taskrole.service.TaskRoleService;
import com.lanou3g.ptp.teacher.mapper.TeacherMapper;
import com.lanou3g.ptp.teacher.service.TeacherService;
import com.lanou3g.ptp.teacher.utils.ExcelUtil;
import com.lanou3g.ptp.user.service.UserService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Reference
    private TaskRoleService taskRoleService;

    @Reference
    private RoleTeacherService roleTeacherService;

    @Reference
    private SchoolService schoolService;

    @Reference
    private CollegeService collegeService;

    @Reference
    private UserService userService;

    @Reference
    private BaseService baseService;

    @Reference
    private TeacherService teacherService;


    @Value("${REDIS_TEACHER_KEY_PREFIX}")
    private String REDIS_TEACHER_KEY_PREFIX;

    @Value("${REDIS_TEACHER_KEY_EXPIRE}")
    private String REDIS_TEACHER_KEY_EXPIRE;

    // 添加教师
    @Override
    public void insert(Teacher teacher) {
        teacherMapper.add(teacher);
    }

    // 查询所有教师
    @Override
    public PageInfo<Teacher> findAll(Integer page, Integer size) {

        PageHelper.startPage(page, size);
        List<Teacher> teacherList = teacherMapper.search();
        return new PageInfo<>(teacherList);

    }

    // 通过id查询教师
    @Override
    public Teacher findById(Long id) {

        // 设置key
        String s1 = REDIS_TEACHER_KEY_PREFIX + id;
        // 根据key，查询redis中是否存在数据
        String s2 = redisTemplate.opsForValue().get(s1);
        if (s2 == null) {
            // 通过id查询教师
            Teacher teacher = teacherMapper.findById(id);
            // 将查询到的Teacher对象序列化为JSON字符串
            String s = JSON.toJSONString(teacher);
            redisTemplate.opsForValue().set(s1, s, 10, TimeUnit.SECONDS);
            return teacher;
        } else {
            // redis中存在数据，刷新过期时间
            redisTemplate.expire(s1, 10, TimeUnit.SECONDS);
            // 返回对象
            return JSON.parseObject(s2, Teacher.class);
        }

    }

    // 根据名字查询教师
    @Override
    public PageInfo<Teacher> findByKeyword(Integer page, Integer size, String keyword) {
        PageHelper.startPage(page, size);
        List<Teacher> list = new ArrayList<>();
        List<User> users = userService.userByName("%" + keyword + "%");
        for (User user : users) {
            Teacher teacher = teacherMapper.findById(user.getId());
            teacher.setUser(user);
            list.add(teacher);
        }
        return new PageInfo<>(list);
    }

    // 通过id删除教师
    @Override
    public void deleteById(Long id) {
        teacherMapper.minus(id);
    }

    // 通过id更改
    @Override
    public void updateById(Long id) {
        teacherMapper.update(id);
    }

    // 通过id批量删除
    @Override
    public void deleteByIds(Long[] ids) {
        teacherMapper.deleteByIds(ids);
    }

    // 生成Excel表格
    @Override
    public void excelPoi(List<Teacher> teachers) {

        //try {
        // 创建一个sheet
        HSSFWorkbook sheets = new HSSFWorkbook();
        Sheet sheet = sheets.createSheet("sheet1");
        int i = 1;

        Row roww = sheet.createRow(0);
        sheet.setColumnWidth(0, 25 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 30 * 256);
        sheet.setColumnWidth(3, 30 * 256);
        sheet.setColumnWidth(4, 30 * 256);
        // 设置行的高度
        roww.setHeightInPoints(30);
        roww.createCell(0).setCellValue("id");
        roww.createCell(1).setCellValue("姓名");
        roww.createCell(2).setCellValue("性别");
        roww.createCell(3).setCellValue("手机号");
        roww.createCell(4).setCellValue("教师类型");


        // 遍历teacher，给teacher的User属性赋值
        for (Teacher teacher : teachers) {
            User user = userService.userById(teacher.getId());
            teacher.setUser(user);
        }

        for (Teacher teacher : teachers) {

            Row row = sheet.createRow(i);
            sheet.setColumnWidth(0, 25 * 256);
            sheet.setColumnWidth(1, 30 * 256);
            sheet.setColumnWidth(2, 30 * 256);
            sheet.setColumnWidth(3, 30 * 256);
            sheet.setColumnWidth(4, 30 * 256);
            // 设置行的高度
            row.setHeightInPoints(30);

            HSSFCreationHelper creationHelper = sheets.getCreationHelper();

            /*设置单元格样式*/

            // 单元格对齐方式
            HSSFCellStyle cellStyle = sheets.createCellStyle();
            // 水平对齐居中
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            // 垂直居中
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 设置字体样式风格
            HSSFCellStyle cellStyle1 = sheets.createCellStyle();
            // 创建字体样式
            HSSFFont font = sheets.createFont();
            // 设置字体样式
            font.setFontName("仿宋");
            // 设置字号
            font.setFontHeightInPoints((short) 16);
            // 设置字体颜色
            font.setColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
            // 将字体样式放入cellStyle1
            cellStyle1.setFont(font);

            if (i != 0) {
                // id
                Cell cell = row.createCell(0);
                cell.setCellValue(teacher.getId());
                cell.setCellStyle(cellStyle);
                cell.setCellStyle(cellStyle1);

                // 姓名
                Cell cell1 = row.createCell(1);
                cell1.setCellValue(teacher.getUser().getName());
                cell1.setCellStyle(cellStyle);
                cell1.setCellStyle(cellStyle1);

                // 性别
                Cell cell2 = row.createCell(2);
                String string = null;
                if (teacher.getGender() == 0) {
                    string = "男";
                } else {
                    string = "女";
                }
                cell2.setCellValue(string);
                cell2.setCellStyle(cellStyle);
                cell2.setCellStyle(cellStyle1);

                // 手机号
                Cell cell3 = row.createCell(3);
                cell3.setCellValue(teacher.getUser().getTel());
                cell3.setCellStyle(cellStyle);
                cell3.setCellStyle(cellStyle1);

                // 教师类型
                Cell cell4 = row.createCell(4);
                String str = null;

                if (teacher.getType() == 0) {
                    str = "本校教师";
                } else {
                    str = "校外教师";
                }

                cell4.setCellValue(str);
                cell4.setCellStyle(cellStyle);
                cell4.setCellStyle(cellStyle1);

            }
            i++;
        }


        // 设置Excel表格存储路径
        FileOutputStream stream = null;
        try {
            stream = new FileOutputStream("D:\\用户信息表1.xls");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            sheets.write(stream);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    // 导出Excel
    @Override
    public List<Teacher> getData(Long[] ids) {

        List<Teacher> teacherList = null;

        if (ids != null) {
            teacherList = teacherMapper.getData(ids);
            excelPoi(teacherList);
        } else {
            teacherList = teacherMapper.search();
            excelPoi(teacherList);
        }

        return teacherList;
    }


    // 解析导入老师
    @Override
    public boolean excelToTeacherInfo(byte[] bytes) {

        InputStream teacherUploadFile = new ByteArrayInputStream(bytes);

        List<Teacher> teachers = new ArrayList<>();

        try {

            boolean isExcel2003 = false;
            Workbook wb = null;

            if (isExcel2003) {
                wb = new HSSFWorkbook(teacherUploadFile);
            } else {
                wb = new XSSFWorkbook(teacherUploadFile);
            }

            Sheet sheet = wb.getSheetAt(0);

            if (sheet != null) {

                // rowNum从第2行开始循环,排除表头
                for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {

                    Row row = sheet.getRow(rowNum);

                    // 将循环得到的信息存储到对象中
                    Teacher teacher = new Teacher();
                    User user = new User();

                    String noExcel = ExcelUtil.getCellValue(row.getCell(0));
                    user.setNo(noExcel);

                    String nameExcel = ExcelUtil.getCellValue(row.getCell(1));
                    user.setName(nameExcel);

                    String genderExcel = ExcelUtil.getCellValue(row.getCell(2));
                    if ("男".equals(genderExcel)) {
                        teacher.setGender(0);
                    } else if ("女".equals(genderExcel)) {
                        teacher.setGender(1);
                    }

                    String telExcel = ExcelUtil.getCellValue(row.getCell(3));
                    user.setTel(telExcel);

                    String typeExcel = ExcelUtil.getCellValue(row.getCell(4));
                    if ("校内教师".equals(typeExcel)) {
                        teacher.setType(0);
                    } else if ("校外教师".equals(typeExcel)) {
                        teacher.setType(1);
                    }

                    String schoolExcel = ExcelUtil.getCellValue(row.getCell(5));
                    teacher.setSchoolId(schoolService.findByName(schoolExcel).getId());

                    String collegeExcel = ExcelUtil.getCellValue(row.getCell(6));
                    teacher.setCollegeId(collegeService.findByName(collegeExcel).getId());

                    String teachSectionExcel = ExcelUtil.getCellValue(row.getCell(7));
                    teacher.setTeachsection(teachSectionExcel);

                    String baseExcel = ExcelUtil.getCellValue(row.getCell(8));
                    List<Base> basesList = baseService.findByName(baseExcel);
                    for (Base base : basesList) {
                        teacher.setBaseId(base.getId());
                    }

                    teacher.setCreateTime(new Date());
                    teacher.setUpdateTime(new Date());

                    user.setCreateTime(new Date());
                    user.setUpdateTime(new Date());

                    teacher.setStatus(1);
                    user.setStatus(1);
                    teacher.setUser(user);
                    Long aLong = userService.addUser(user);
                    teacher.setId(aLong);
                    teachers.add(teacher);

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return teacherExcel(teachers);

    }

    @Override
    public boolean teacherExcel(List<Teacher> teachers) {

        // 记录 加入条数总数
        int sum = 0;
        boolean b = false;
        // 加入数据
        for (Teacher teacher : teachers) {
            insert(teacher);
        }
        // 判定是否加入条数和信息总数一直  返回结果
        if (sum == teachers.size()) {
            b = true;
        }
        return b;
    }

    @Override
    public List<Long> findByTaskId(Long taskId) {
        List<TaskRole> taskRoles = taskRoleService.findByTaskId(taskId);
        List<Long> roleIds = new ArrayList<>();
        List<Long> teacherIds = new ArrayList<>();
        List<Long> teacherIds1 = new ArrayList<>();
        for (TaskRole taskRole : taskRoles) {
            Long roleId = taskRole.getRoleId();
            roleIds.add(roleId);
        }
        System.out.println(roleIds + ";;;");
        for (Long roleId : roleIds) {
            List<RoleTeacher> roleTeachers = roleTeacherService.findByRoleId(roleId);
            for (RoleTeacher roleTeacher : roleTeachers) {
                Long teacherId = roleTeacher.getTeacherId();
                teacherIds.add(teacherId);
            }
        }
        for (Long teacherId : teacherIds) {
            List<Teacher> teachers = teacherMapper.findByIdAndType(teacherId);
            for (Teacher teacher : teachers) {
                Long id = teacher.getId();
                teacherIds1.add(id);
            }
        }
        return teacherIds1;
    }

    @Override
    public List<Teacher> findByIdAndType(Long teacherId) {
        List<Teacher> teachers = teacherMapper.findByIdAndType(teacherId);
        return teachers;
    }

    @Override
    public byte[] excelTeacherModel() {

        // 创建一个新的工作簿
        XSSFWorkbook sheets = new XSSFWorkbook();
        Sheet sheet = sheets.createSheet("码页");

        // 负责表格对齐方式
        CellStyle cellStyle1 = sheets.createCellStyle();
        // 设置单元格水平方向对齐方式居中
        cellStyle1.setAlignment(HorizontalAlignment.LEFT);
        // 设置单元格垂直方向对齐方式居中
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);

        // 设置表头字体样式
        XSSFCellStyle cellStyle4 = sheets.createCellStyle();
        // 设置字体样式
        XSSFFont font1 = sheets.createFont();
        font1.setFontName("微软雅黑");
        // 设置字号
        font1.setFontHeightInPoints((short) 12);
        // 设置字体颜色
        font1.setColor(HSSFColor.HSSFColorPredefined.BLUE.getIndex());
        // 字体风格放入风格
        cellStyle4.setFont(font1);

        Row row1 = sheet.createRow(0);
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 25 * 256);
        sheet.setColumnWidth(3, 25 * 256);
        sheet.setColumnWidth(4, 20 * 256);
        sheet.setColumnWidth(5, 20 * 256);
        sheet.setColumnWidth(6, 15 * 256);
        row1.setHeightInPoints(30);

        row1.createCell(0).setCellValue("工号");
        row1.createCell(1).setCellValue("姓名");
        row1.createCell(2).setCellValue("性别");
        row1.createCell(3).setCellValue("手机号");
        row1.createCell(4).setCellValue("教师类型");
        row1.createCell(5).setCellValue("学校");
        row1.createCell(6).setCellValue("学院");
        row1.createCell(7).setCellValue("教研室");
        row1.createCell(8).setCellValue("实习基地");

        row1.setRowStyle(cellStyle1);
        row1.setRowStyle(cellStyle4);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            sheets.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return outputStream.toByteArray();

    }

}
